"""
Case Type   : 操作系统类-文件系统故障
Case Name   : 级联备build时 注入故障系统文件句柄耗尽
Create At   : 2021/7/19
Owner       : @wan005
Description :
    1、将备1build为级联备
    2、级联备注入文件句柄耗尽故障
    3、级联备上执行gs_ctl build
    4、清理故障，
    5、再次build
    6、执行TPCC
    7、检查数据一致性
    8、恢复环境
Expect      :
    1、将备1build为级联备成功
    2、故障注入成功
    3、build失败
    4、清理故障成功
    5、build成功
    6、执行TPCC成功
    7、数据一致
    8、恢复环境
History     :
    Modified by @wan005 2021/8/23: 优化故障清理
    Modified by @wan005 2021/12/9: 优化故障清理后重启数据库
"""
import time
import unittest

from testcase.utils.ComThread import ComThread
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node, macro


class ReliabilityFileSystem(unittest.TestCase):
    nodes = ("PrimaryDbUser", "Standby1DbUser", "Standby2DbUser")

    @RestartDbCluster(*nodes)
    def setUp(self):
        self.log = Logger()
        self.primary_sh = CommonSH(self.nodes[0])
        self.sta1_sh = CommonSH(self.nodes[1])
        self.primary_root_node = Node(node="PrimaryRoot")
        self.sta1_root_node = Node(node="Standby1Root")
        self.sta1_node = Node(node="Standby1DbUser")
        self.constant = Constant()
        self.com = Common()
        self.log.info("setUp-实例化:ok")

        self.log.info("Opengauss_Reliability_OS_File_System_Case021:开始执行")
        self.inject_cmd = f"rfile_deplenish (timeout) values (120)"

    def test_main(self):
        self.log.info("步骤1:将备1 build为级联备")
        result = self.sta1_sh.executeGsctl("build",
                                           "server started",
                                           param="-M cascade_standby",
                                           get_detail=True)
        self.log.info(result)
        self.assertIn("server started", result)

        status = self.sta1_sh.exec_refresh_conf()
        self.assertTrue(status)

        status = self.sta1_sh.getDbClusterStatus("detail")
        self.log.info(status)
        self.assertIn("S Cascade Normal", status)

        try:
            self.log.info("步骤2:级联备注入句柄耗尽故障")
            self.log.info("注入故障")
            session = ComThread(self.com.cfe_inject,
                                args=(self.sta1_root_node,
                                      self.inject_cmd))
            session.setDaemon(True)
            session.start()

            session.join(60)
            result = session.get_result()
            self.log.info(result)

            self.log.info("步骤3:级联备上执行gs_ctl build")
            result = self.sta1_sh.executeGsctl("build",
                                               "server started",
                                               param="-M cascade_standby",
                                               get_detail=True)
            self.log.info(result)
            self.assertIn("Too many open files", result)
            self.assertNotIn("server started", result)

        finally:
            self.log.info("步骤4:清除故障")
            time.sleep(120)
            result = self.primary_sh.stopDbCluster(get_detail=True)
            self.log.info(result)
            result = self.primary_sh.startDbCluster()
            self.log.info(result)

        self.log.info("步骤5:故障清理后，级联备上再次执行gs_ctl build")
        result = self.sta1_sh.executeGsctl("build",
                                           "server started",
                                           param="-M cascade_standby",
                                           get_detail=True)
        self.log.info(result)
        self.assertIn("server started", result)
        self.assertNotIn("Too many open files", result)

        db_status = self.primary_sh.getDbClusterStatus("detail")
        self.log.info(db_status)
        self.assertTrue("Degraded" in db_status or "Normal" in db_status)

        self.log.info("步骤6:运行TPCC")
        result = self.com.startTPCC(self.primary_root_node, macro.TPCC_PATH)
        self.log.info(result)
        self.assertIn(self.constant.TPCC_SUCCESS_MSG, result)

        self.log.info("检查主备是否同步")
        time.sleep(10)
        res = self.primary_sh.check_location_consistency("primary", 2)
        self.assertTrue(res)
        res = CommonSH(self.nodes[1]).check_cascade_standby_consistency()
        self.assertTrue(res)
        self.log.info("备2-级联备检查同步:ok")

        self.log.info('步骤7:检查数据一致性')
        nodes = (Node(self.nodes[0]), Node(self.nodes[1]),
                 Node(self.nodes[2]))
        flag = self.com.check_data_sample_by_all(r'\d', *nodes)
        self.assertTrue(flag)
        table_dict = self.com.format_sql_result(
            self.primary_sh.executDbSql(r'\d'))
        table_name = table_dict.get('Name')
        for name in table_name:
            select_sql = f'select count(*) from {name};'
            flag = self.com.check_data_sample_by_all(select_sql, *nodes)
            self.assertTrue(flag)

    def tearDown(self):
        self.log.info("步骤8:环境清理")
        time.sleep(120)
        self.log.info("故障已清理")
        result = self.primary_sh.stopDbCluster(get_detail=True)
        self.log.info(result)
        result = self.primary_sh.startDbCluster()
        self.log.info(result)

        status = self.sta1_sh.getDbClusterStatus("detail")
        self.log.info(status)
        if "S Cascade Normal" in status:
            result = self.sta1_sh.executeGsctl("build",
                                               "server started",
                                               param="-b full",
                                               get_detail=True)
            self.log.info(result)
            status = self.sta1_sh.exec_refresh_conf()
            self.log.info(status)
        status = self.sta1_sh.getDbClusterStatus("detail")
        self.log.info(status)
        result = Node(self.nodes[1]).sh("date").result()
        self.assertNotIn("Too many open files", result)
        self.log.info("Opengauss_Reliability_OS_File_System_Case021:执行完成")
